package com.zhengshang.api.controller.goodsshop;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;
import com.zhengshang.api.domain.AppTaoRelation;
import com.zhengshang.api.service.IAppTaoOrderService;
import com.zhengshang.api.service.IAppTaoRelationService;
import com.zhengshang.common.core.domain.AjaxResult;
import com.zhengshang.common.core.domain.entity.SysUser;
import com.zhengshang.common.core.domain.model.LoginAppUser;
import com.zhengshang.common.core.redis.RedisCache;
import com.zhengshang.security.service.TokenService;
import com.zhengshang.system.service.ISysConfigService;
import com.zhengshang.third.taobao.TaoBaoUtils;
import com.zhengshang.third.wikeyun.WikeyunApi;
import com.zhengshang.third.wikeyun.WikeyunUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

/**
 * @author: zyf
 * @date: 2018/11/9 15:43
 * @description: 基础服务模块接口, 不需要登录鉴权的接口
 */
@Api(tags = "淘宝接口")
@Controller
@RequestMapping("/taobao")
public class AppTaoBaoController {

    @Autowired
    private TaoBaoUtils taoBaoUtils;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private WikeyunUtils wikeyunUtils;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private IAppTaoRelationService appTaoRelationService;

    @Autowired
    private IAppTaoOrderService appTaoOrderService;

    @Autowired
    private RedisCache redisCache;


    /**
     * 获取授权Url
     */
    @GetMapping(value = "/getTaoBaoAccessTokenUrl")
    @ResponseBody
    public AjaxResult getTaoBaoAccessTokenUrl(HttpServletRequest request, String state) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        SysUser appUser = loginAppUser.getAppUser();
        Long userId = appUser.getUserId();
        String domainUrl = sysConfigService.selectConfigByKey("sys.domain.name");
        String callbackUrl = domainUrl + "api/taobao/getTaoBaoAccessToken?userId=" + userId;
        String oauthUrl = taoBaoUtils.getAppOauthUrl(callbackUrl, state);
        return AjaxResult.success("获取成功", oauthUrl);
    }


    /**
     * 获取accessToken
     */
    @GetMapping(value = "/getTaoBaoAccessToken")
    @ResponseBody
    public AjaxResult getTaoBaoAccessToken(Long userId, String code) {
        AjaxResult ajaxResult = taoBaoUtils.getAccessToken(code);
        Integer ajaxCode = TypeUtils.castToInt(ajaxResult.get("code"));
        if (ajaxCode == 200) {
            JSONObject jsonObject = (JSONObject) ajaxResult.get("data");
            //淘宝用户授权的token
            String accessToken = jsonObject.getString("access_token");
            //token过期时间
            Long expiresIn = jsonObject.getLong("expires_in");
            taoBaoUtils.savePublisher(userId, accessToken, "优惠牛线上", "优惠牛线上");
        }
        return ajaxResult;
    }


    /**
     * 获取淘宝账号授权给微客云集的accessToken
     */
    @GetMapping(value = "/getWiKeYunAccessTokenUrl")
    @ResponseBody
    public AjaxResult getWiKeYunAccessTokenUrl(HttpServletRequest request) {
        return AjaxResult.success(taoBaoUtils.getAccessTokenUrl());
    }


    /**
     * 微客云集淘宝回调地址
     * 获取淘宝授权信息
     */
    @GetMapping(value = "/getWkYTaoBaoAccessToken")
    @ResponseBody
    public AjaxResult getWkYTaoBaoAccessToken(String token, String refresh_token, String taobao_user_nick, String taobao_user_id) {
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("refresh_token", refresh_token);
        map.put("taobao_user_nick", taobao_user_nick);
        map.put("taobao_user_id", taobao_user_id);
        redisCache.setCacheObject(taoBaoUtils.weiKeYunTaobBaoRedisKey, map, 60 * 60 * 24 * 30, TimeUnit.SECONDS);
        return AjaxResult.success("授权成功");
    }

    /**
     * 刷新accessToken
     */
    @GetMapping(value = "/refreshToken")
    @ResponseBody
    public AjaxResult refreshToken(HttpServletRequest request, String refreshToken) {
        return taoBaoUtils.refreshToken(refreshToken);
    }


    /**
     * 物料搜索
     */
    @GetMapping(value = "/materialOtionalSearch")
    @ResponseBody
    public AjaxResult materialOtionalSearch(String goodsName, Long pageNo, Boolean isTmall, String orderBy, String sort, Boolean hasCoupon) {
        return taoBaoUtils.materialOtionalSearch(goodsName, pageNo, isTmall, orderBy, sort, hasCoupon);
    }


    /**
     * 高效转链接
     */
    @ApiOperation(value = "根据淘宝商品id、PID、授权信息转链接获得淘宝客链接、二合一券链接")
    @ResponseBody
    @GetMapping("/transform")
    public AjaxResult taobaoTransform(HttpServletRequest request, String numIid) {
        boolean hasKey = redisCache.hasKey(taoBaoUtils.weiKeYunTaobBaoRedisKey);
        if (!hasKey) {
            return AjaxResult.error("授权给微客云的淘宝账号的access_token已过期");
        }
        Map<String, String> map = redisCache.getCacheObject(taoBaoUtils.weiKeYunTaobBaoRedisKey);
        String accessToken = map.get("token");
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        SysUser appUser = loginAppUser.getAppUser();
        Long userId = appUser.getUserId();
        AppTaoRelation appTaoRelation = appTaoRelationService.findByUserId(userId);
        Long specialId = appTaoRelation.getSpecialId();
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("num_iid", numIid);
        params.put("pid", taoBaoUtils.channelPid);
        //会员Id
        params.put("special_id", specialId);
        //渠道Id
        params.put("relation_id", "");
        params.put("access_token", accessToken);
        params.put("external_id", appUser.getUserId());
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.taobaoTransform);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }

    /**
     * 链接解析出商品id
     */
    @ApiOperation(value = "根据淘宝客链接解析出淘宝商品原始ID")
    @ResponseBody
    @GetMapping("/extractItem")
    public AjaxResult taobaoExtractItem(String clickUrl) {
        TreeMap<String, Object> params = new TreeMap<>();
        params.put("click_url", clickUrl);
        String result = wikeyunUtils.sendPostRequest(params, WikeyunApi.taobaoExtractItem);
        JSONObject jsonObject = JSONObject.parseObject(result);
        return wikeyunUtils.converAjaxResult(jsonObject);
    }

    /**
     * 链接解析出商品id
     */
    @ApiOperation(value = "根据淘宝客链接解析出淘宝商品原始ID")
    @ResponseBody
    @GetMapping("/queryOrderList")
    public AjaxResult queryOrderList(String endTime, String startTime) {
        return taoBaoUtils.queryOrderList(1, "", 1, 20, null, "", endTime, startTime, -1, 3);
    }

    /**
     * 绑定系统用户和淘宝私域用户
     */
    @ApiOperation(value = "根据淘宝客链接解析出淘宝商品原始ID")
    @ResponseBody
    @PostMapping("/savePublisher")
    public AjaxResult savePublisher(HttpServletRequest request, String taoBaoAccessToken) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        Long userId = loginAppUser.getAppUser().getUserId();
        return taoBaoUtils.savePublisher(userId, taoBaoAccessToken, "优惠牛线上", "优惠牛线上");
    }

    /**
     * 查询用户订单
     */
    @ApiOperation(value = "根据淘宝客链接解析出淘宝商品原始ID")
    @ResponseBody
    @GetMapping("/queryUserOrder")
    public AjaxResult queryUserOrder(HttpServletRequest request) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        Long userId = loginAppUser.getAppUser().getUserId();
        List<Map> mapList = appTaoOrderService.queryTaoOrderByUserId(userId);
        return AjaxResult.success(mapList);
    }

    /**
     * 活动转链接
     */
    @ApiOperation(value = "活动转链接")
    @ResponseBody
    @GetMapping("/getActivityInfo")
    public AjaxResult getActivityInfo(HttpServletRequest request) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        Long userId = loginAppUser.getAppUser().getUserId();
        AjaxResult activityInfo = taoBaoUtils.getActivityInfo(taoBaoUtils.elmActivityMaterialId, userId);
        return AjaxResult.success(activityInfo);
    }

    /**
     * 活动转链接
     */
    @ApiOperation(value = "活动转链接")
    @ResponseBody
    @GetMapping("/optimusMaterial")
    public AjaxResult optimusMaterial(HttpServletRequest request) {
        LoginAppUser loginAppUser = tokenService.getLoginAppUser(request);
        Long userId = loginAppUser.getAppUser().getUserId();
        return taoBaoUtils.optimusMaterial(27446L);
    }

}
